<template>
	<view class="page">
		<free-nav-bar title="我的收藏" showBack :showRight="false"></free-nav-bar>
		
		<view class="pt-3 px-3" v-for="(item, index) in list" :key="index" 
		@longpress="long(item, index)" @click="send(item)" >
			<view class="bg-white rounded p-3">
				<!-- 文字 -->
				<view class="py-2" v-if="item.type === 'text'">
					<text class="font">{{item.data}}</text>
				</view>
				<!-- 图片|表情 -->
				<free-image v-else-if="item.type === 'image' || item.type === 'emoticon'" 
				:src="item.data"></free-image>
				<!-- 视频 -->
				<video v-else-if="item.type === 'video'" :src="item.data" :poster="item.options.poster" controls style="width: 500rpx; height: 400rpx;"></video>
			</view>
		</view>
		
		<!-- 上拉加载 -->
		<view class="flex align-center justify-center py-4 bg-light mt-2" v-if="list.length >= 10">
			<text class="text-muted font">{{loadmore}}</text>
		</view>
	</view>
</template>

<script>
	import freeNavBar from "@/components/free-ui/free-nav-bar.vue"
	import freeImage from "@/components/free-ui/free-image.vue"
	import $H from "@/common/free-lib/request.js"
	export default {
		data() {
			return {
				list:[],
				page: 1,
				loadmore: "上拉加载更多",
				type: ""
			}
		},
		onLoad(e) {
			if(e.type){
				this.type = e.type
			}
			this.page = 1
			this.getData()
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.page = 1
			this.getData().then(res=>{
				// 关闭下拉刷新
				uni.stopPullDownRefresh()
			})
		},
		// 上拉加载更多
		onReachBottom() {
			this.page++
			console.log("触发上拉加载更多...")
			this.getData().catch(err=>{
				this.page--
			})
		},
		methods: {
			// 发送收藏
			send(item){
				if(this.type !== 'send') return;
				
				uni.$emit('sendItem',{
					sendType: "fava",
					...item
				})
				uni.navigateBack()
			},
			// 长按删除
			long(item, index){
				let that = this;
				uni.showActionSheet({
					itemList:['删除'],
					success(res) {
						if(res.tapIndex !== 0) return;
						uni.showModal({
							content: '是否要删除',
							success: res => {
								if(res.cancel) return;
								$H.post('/fava/destroy', {
									id: item.id
								}).then(res=>{
									uni.showToast({
										title: '删除成功'
									})
									that.list.splice(index, 1)
								})
							}
						});
					}
				})
			},
			// 获取数据
			getData(){
				return new Promise((result, reject)=>{
					$H.get('/fava/'+this.page).then(res=>{
						let list = res.map(item=>{
							item.options = JSON.parse(item.options)
							return item
						})
						this.list = this.page === 1 ? list : [...this.list, ...list]
						this.loadmore = this.list.length == this.page * 10 ? '上拉加载更多' : '没有更多了'
						result(res)
					}).catch(err=>{
						reject(err)
					})
				})
			}
		},
		components:{
			freeNavBar,
			freeImage
		}
	}
</script>

<style>

</style>
